package cn.sell.comm.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.HashMap;

/**
 * 用于AES的加密与解密
 */
public class AESUtil {
    private static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static HashMap<byte[], Cipher> encryptCipherMap = new HashMap<byte[], Cipher>();
    private static HashMap<byte[], Cipher> decryptCipherMap = new HashMap<byte[], Cipher>();


    // 初始化
    private static void init(byte[] key) throws Exception {

        if (encryptCipherMap.get(key) == null) {//加密
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key);
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher encryptCipher = Cipher.getInstance(algorithmStr);
            encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            encryptCipherMap.put(key, encryptCipher);
        }

        if (decryptCipherMap.get(key) == null) {//解密
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key);
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher decryptCipher = Cipher.getInstance(algorithmStr);
            decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            decryptCipherMap.put(key, decryptCipher);
        }
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) throws Exception {
        byte[] encryptedText = null;
        init(keyBytes);
        Cipher cipher = (Cipher) encryptCipherMap.get(keyBytes);
        encryptedText = cipher.doFinal(content);
        return encryptedText;
    }

    // 解密为byte[]
    private static byte[] decrypt(byte[] content, byte[] keyBytes) throws Exception {
        byte[] originBytes = null;
        init(keyBytes);
        Cipher cipher = (Cipher) decryptCipherMap.get(keyBytes);
        originBytes = cipher.doFinal(content);
        return originBytes;
    }

    public static String encrypt(String content, String key) throws Exception {
        byte[] resultByte = encrypt(content.getBytes("UTF-8"), key.getBytes());
        return parseByte2HexStr(resultByte);
    }

    public static String decrypt(String content, String key) throws Exception {
        byte[] inputByte = parseHexStr2Byte(content);
        byte[] resultByte = decrypt(inputByte, key.getBytes());
        return new String(resultByte, "UTF-8");
    }

    public static String parseByte2HexStr(byte buf[]) throws Exception {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

//    //hkt内部加密，使用默认密码
//    public static String encryptHKT(String value,PasswordEnum key) throws NoSuchAlgorithmException, UnsupportedEncodingException, Exception{
//    	return encrypt(value, genKey(key));
//    }
//    //hkt内部解密，使用默认密码
//    public static String decryptHKT(String value,PasswordEnum key) throws NoSuchAlgorithmException, UnsupportedEncodingException, Exception{
//    	return decrypt(value, genKey(key));
//    }

//  //生成密码
//  private static String genKey(PasswordEnum key) throws NoSuchAlgorithmException, UnsupportedEncodingException{
////	  return SHAUtil.encrypt(key==null?null:key.getPassword(),SHAUtil.SHA_256);
//	  return key==null?"":key.getPassword();
//  }
}

